package org.openrbac.rbac.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.openrbac.rbac.constant.CommonConstant;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author bapie
 */
@Component
public class JwtUtil {
    //有效期为1天
    public static final Long JWT_TTL = 1000*60*60*24L;
    //设置秘钥明文
    public static final String JWT_KEY = "PanChen";

    private SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    public String createJwt(String subject, Long ttlMillis) {
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        long expMillis = nowMillis + JWT_TTL;
        Date expDate = new Date(expMillis);
        SecretKey secretKey = generalKey();

        JwtBuilder builder = Jwts.builder()
                //唯一的ID
                .setId(UUID.randomUUID().toString())
                // 主题  可以是JSON数据
                .setSubject(subject)
                // 签发者
                .setIssuer("PanChen")
                // 签发时间
                .setIssuedAt(now)
                //使用HS256对称加密算法签名, 第二个参数为秘钥
                .signWith(signatureAlgorithm, secretKey)
                // 设置过期时间
                .setExpiration(expDate);
        return builder.compact();
    }

    public String createJwt(String subject) {
        return createJwt(subject, null);
    }

    public Claims parseJwt(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        SecretKey secretKey = generalKey();
        Claims claims;
        claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        if (username != null) {
            return username.replaceAll("\"", "");
        } else {
            return null;
        }
    }

    /**
     * 去除无效前缀
     * @param request
     * @return
     */
    public String extractAuthToken(HttpServletRequest request) {
        String authToken = request.getHeader(CommonConstant.TOKEN_HEADER);
        if (authToken != null && authToken.startsWith(CommonConstant.TOKEN_STARTS)) {
            return authToken.substring(7);
        }
        return null;
    }
    public String extractAuthToken(String token) {
        if (token != null && token.startsWith(CommonConstant.TOKEN_STARTS)) {
            return token.substring(7);
        }
        return null;
    }
}
